package com.voxel.sense.infomsg.module.publish;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.support.v7.widget.AppCompatAutoCompleteTextView;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.TextView;

import com.example.com.common.app.BViewActivity;
import com.example.com.common.utils.FileUtils;
import com.example.com.common.utils.IntentUtils;
import com.example.com.common.utils.NetworkUtils;
import com.example.com.common.utils.SizeUtils;
import com.example.com.common.utils.TimeUtils;
import com.example.com.common.utils.ToastUtil;
import com.example.com.common.view.dialog.DialogCallBack;
import com.example.com.common.view.dialog.DialogImpl;
import com.voxel.sense.infomsg.R;
import com.voxel.sense.infomsg.data.FileImageInfo;
import com.voxel.sense.infomsg.data.bean.ConditionBean;
import com.voxel.sense.infomsg.utils.AppFileUtil;
import com.voxel.sense.infomsg.utils.FileProvider7;
import com.voxel.sense.infomsg.view.MyGridView;
import com.voxel.sense.infomsg.view.decoration.ItemDivider;
import com.voxel.sense.infomsg.view.decoration.LinearItemDecoration;
import com.voxel.sense.infomsg.view.titlebar.TextTitleBar;
import com.voxel.sense.infomsg.widget.CommonImagePagerActivity;
import com.voxel.sense.infomsg.widget.adapter.FileGalleryAdapter;
import com.voxel.sense.infomsg.widget.adapter.AbsPickRecyclerAdapter;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import butterknife.BindView;
import butterknife.OnItemClick;
import cyy.example.com.facotry.Factory;
import cyy.example.com.facotry.constants.Constants;
import cyy.example.com.facotry.constants.IntentConstants;
import cyy.example.com.facotry.model.api.response.FirmNameByIdEntity;
import droidninja.filepicker.FilePickerBuilder;
import droidninja.filepicker.FilePickerConst;
import droidninja.filepicker.utils.Orientation;

public class PublishFileActivity extends BViewActivity<PublishContract.Presenter>
        implements PublishContract.View {

    @BindView(R.id.gridview_image)
    MyGridView gridview_image; //图片grid
    @BindView(R.id.btn_submit)
    Button btn_submit;//提交按钮
    @BindView(R.id.et_advice)
    EditText et_advice;
    @BindView(R.id.tv_content_count)
    TextView tv_content_count;//编辑框输入限制提示
    @BindView(R.id.et_name)
    AppCompatAutoCompleteTextView et_name;
    @BindView(R.id.titlebar)
    TextTitleBar titlebar;

    @BindView(R.id.recycle_type)
    RecyclerView recycle_type;

    private FileGalleryAdapter mImageAdapter;


    private File mTakePhotoFile;//拍照获取的文件
    private AbsPickRecyclerAdapter mTypeAdatper;

    private MyArrayAdapterAdapter<FirmNameByIdEntity> mFirmListAdapter;
    private FirmNameByIdEntity mSelectedItem;


    public static void show(Context context) {
        context.startActivity(new Intent(context, PublishFileActivity.class));
    }

    @Override
    protected int getContentLayoutId() {
        return R.layout.activity_publish_file;
    }

    @Override
    protected PublishContract.Presenter initPresenter() {
        return new PublishFilePresenter(this);
    }


    @Override
    protected void initData() {
        super.initData();
        //初始化图片选择模块
        ArrayList<FileImageInfo> lstImageData = new ArrayList<>();
        lstImageData.add(new FileImageInfo(Constants.ADD_FILE, Constants.ADD_FILE));
        //添加一个头显示添加图片的样式
        mImageAdapter = new FileGalleryAdapter(this, lstImageData);
        gridview_image.setAdapter(mImageAdapter);

        titlebar.setTitleText("企业填报");

        //初始化发布类型
        recycle_type.setLayoutManager(new GridLayoutManager(this, 3));
        recycle_type.addItemDecoration(new LinearItemDecoration(R.drawable.recycle_divider_5dp_white));
        mTypeAdatper = new PublishTypeAdatper();
        mTypeAdatper.setSingleSelect(true);
        recycle_type.setAdapter(mTypeAdatper);
        mPresenter.doLoadTypeData();

        //加载公司数据
        mPresenter.doLoadFirmList();
        et_name.setDropDownHeight(SizeUtils.dp2px(150));
        et_name.requestLayout();
        et_name.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                et_name.showDropDown();
            }
        });
    }

    @Override
    protected void initEven() {
        super.initEven();
        et_name.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                //文字改变前，清除之前的选项
                mSelectedItem = null;
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                //没有获取到公司列表，则再次加载公司列表数据
                if (mFirmListAdapter == null || mFirmListAdapter.getCount() < 1) {
                    if (NetworkUtils.isConnected()) {
                        mPresenter.doLoadFirmList();
                    } else {
                        ToastUtil.showToastLong(Factory.app(), R.string.network_unavailable);
                    }
                }
            }
        });


        et_name.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                mSelectedItem = (FirmNameByIdEntity) parent.getItemAtPosition(position);
            }
        });

        btn_submit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String id = "";
                String type = "";
                List selectListData = mTypeAdatper.getSeletedDatas();
                if (selectListData != null && selectListData.size() > 0) {

                    ConditionBean bean = (ConditionBean) selectListData.get(0);
                    type = bean.getTipCode();
                }
                if (mSelectedItem != null) {
                    String companyName = mSelectedItem.getCompanyName();
                    id = mSelectedItem.getCompanyId();

                }

                mPresenter.doSubmitContent(et_advice.getText().toString(), et_name.getText().toString(), id, type,mImageAdapter.getDatasPath());

            }
        });
    }

    @Override
    public void onUpTypeUi(List list) {
        if (mTypeAdatper != null && mTypeAdatper.getItemCount() < 1) {
            mTypeAdatper.replace(list);
        }
    }

    @Override
    public void onShowFirmList(List list) {
        //设置适配器，适配器为全局变量时，add数据时后，调用showDropDown()，下拉列表没有显示。暂时找不到具体原因
        if (mFirmListAdapter == null) {
            mFirmListAdapter = new MyArrayAdapterAdapter<>(this, R.layout.layout_textview_search_tip, list);
            et_name.setAdapter(mFirmListAdapter);
        }
//        mFirmListAdapter.notifyDataSetChanged();
//        mFirmListAdapter.getFilter().filter(et_name.getText());
//        et_name.showDropDown();
    }

    @Override
    public void onShowPickPhotoUI(List<String> list) {
        ArrayList<String> datasPath = mImageAdapter.getDatasPath();
        FilePickerBuilder.getInstance().setMaxCount(Constants.UPLOAD_FILE_MAX_COUNT)
                .setSelectedFiles(datasPath)
                .setActivityTheme(R.style.FilePickerTheme)
                .enableImagePicker(true)
                .enableVideoPicker(false)//是否能视频图片
                .enableCameraSupport(false)//是否有照相item
                .showGifs(false)//是否显示gif图
                .showFolderView(false)//是否显示文件夹
                .enableSelectAll(true)//是否选中全部，这个选中只有没有选中数量的情况下才能使用
                .setCameraPlaceholder(R.mipmap.custom_camera)//相机图片
                .withOrientation(Orientation.UNSPECIFIED)
                .pickPhoto(this);//显示文件
    }


    @OnItemClick({R.id.gridview_image})
    void gridItemClick(GridView view, View childrenView, int position, long id) {
        switch (view.getId()) {
            case R.id.gridview_image://图片item点击事件
                pickClickEvent(position);
                break;
        }
    }

    private void pickClickEvent(int position) {
        if (position == mImageAdapter.getCount() - 1) {
            //点击最后一个，则是添加图片
            List<String> list = new ArrayList<>();
            list.add("拍摄");
            list.add("从相册选中");
            DialogImpl.getInstance().showItemDialog(this, "", list, new DialogCallBack() {
                @Override
                public void onClick(int what) {
                    if (what == 0) {
                        //拍照
                        takePhoto();
                    } else {
                        onShowPickPhotoUI(mImageAdapter.getDatasPath());
                    }
                }
            });
        } else {
            //查看图片
            CommonImagePagerActivity.showImages(PublishFileActivity.this, mImageAdapter.getDatasPath(), position);
        }
    }

    /**
     * 跳转相机
     */
    private void takePhoto() {
        mTakePhotoFile = new File(AppFileUtil.getPhoneImageDir(),
                TimeUtils.getNowString(new SimpleDateFormat("yyyy-MM-ddHHmmss", Locale.getDefault())) + ".jpg");
        Uri uriForFile = FileProvider7.getUriForFile(mTakePhotoFile);
        Intent intent = IntentUtils.getCaptureIntent(uriForFile);
        startActivityForResult(intent, IntentConstants.REQUEST_CODE_TAKE_PHOTO);
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == FilePickerConst.REQUEST_CODE_PHOTO) {
                ArrayList<String> photoResult = data.getStringArrayListExtra(FilePickerConst.KEY_SELECTED_MEDIA);
                mPresenter.doHandlerSelectPicResult(photoResult);
            } else if (requestCode == IntentConstants.REQUEST_CODE_TAKE_PHOTO) {
                getTakePhoneResult();
            }
        }
    }


    private void getTakePhoneResult() {

        mPresenter.doHanlderTakePhotoResult(mTakePhotoFile);
        if (FileUtils.isFileExists(mTakePhotoFile)) {
            FileImageInfo fileImageInfo = new FileImageInfo(mTakePhotoFile.getName(), mTakePhotoFile.getPath());
            List<FileImageInfo> list = mImageAdapter.getList();
            list.add(list.size() - 1, fileImageInfo);
            mImageAdapter.notifyDataSetChanged();
        }
    }


    @Override
    public void onRefreshSelectPhoto(List list) {
        mImageAdapter.setList(list);
    }

    @Override
    public void onSubmitSuccess() {
        btn_submit.setEnabled(false);
        btn_submit.setText(R.string.publish_file_success);
        finish();
    }

    @Override
    public void onSubmitFailed() {

    }

}

